package org.bulldog.playlist.program;

import org.bulldog.playlist.PlayListBuilder;

import java.util.*;

/**
 * Created by zhanghongbin on 2017/10/17.
 *
 * @author zhanghongbin
 * @version 1.0
 */
 class SpotsCompositePlayListBuilder implements PlayListBuilder<List<Program>, Program> {

    protected List<Program>[] spotsDailyProgramArray;

    public SpotsCompositePlayListBuilder(List<Program>[] sportsDailyProgramArray) {
        this.spotsDailyProgramArray = sportsDailyProgramArray;
    }

    @Override
    public List<Program> build(List<Program> programList) {
        //进行重叠时间节目处理
        List<Program> programs = new SpotsOverlapPlayListBuilder(this.spotsDailyProgramArray).build(programList);
        if (!programs.isEmpty()) {
            //进行节目分离，提炼出插播节目，和插播日常节目
            Map<String, Object> spotsProgramMap = this.extractSpotsProgram(programs);
            programs.clear();
            List<Program> spotsProgramList = new SpotsPlayListBuilder(SpotsDailyPlayListBuilder.INSTANCE.build((List<Program>[]) spotsProgramMap.get("spotsDaily")))
                    .build((List<Program>) spotsProgramMap.get("spots"));
            spotsProgramMap.clear();
            return spotsProgramList;
        }
        return programs;
    }

    /**
     * @param programs
     * @return
     */
    final protected Map<String, Object> extractSpotsProgram(List<Program> programs) {
        Map<String, Object> result = new HashMap();
        List<List<Program>> sportsDailyProgramList = new ArrayList<>();
        List<Program> programList = new ArrayList<>();
        for (int i = 0; i < programs.size(); i++) {
            Program program = programs.get(i);
            if (program.getId().length() == 0) {
                int index = Integer.parseInt(program.getParams().get("@@index").toString());
                sportsDailyProgramList.add(this.deepCopy(this.spotsDailyProgramArray[index],
                        program.getStartTime(), program.getEndTime()));
            } else {
                programList.add(program);
            }
        }
        result.put("spots", programList);
        result.put("spotsDaily", sportsDailyProgramList.toArray(new List[sportsDailyProgramList.size()]));
        return result;
    }

    private List<Program> deepCopy(List<Program> programList, String startTime, String endTime) {
        List<Program> programs = new ArrayList<>();
        if (programList.isEmpty()) return programs;
        Program program = (Program) programList.get(0).clone();
        program.setStartTime(startTime);
        program.setEndTime(endTime);
        programs.add(program);
        for (int i = 1; i < programList.size(); i++) {
            programs.add(programList.get(i));
        }
        return programs;
    }
}
